package org.example.websocket;


import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws")  // 接收前端 ws://localhost:8081/ws 请求的地址
public class WebSocketServerTest {
    
    // 用来存储所有连接的客户端会话
    private static final Map<String, Session> sessions = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("有新的WebSocket连接建立：" + session.getId());
        sessions.put(session.getId(), session);
        
        // 发送连接成功消息
        JSONObject message = new JSONObject();
        message.put("type", "CONNECTED");
        message.put("message", "WebSocket连接成功");
        message.put("sessionId", session.getId());
        sendMessage(session, message.toJSONString());
    }
    
    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket连接关闭：" + session.getId());
        sessions.remove(session.getId());
    }
    
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到消息：" + message);
        System.out.println("=====WebSocket会话详细信息=====");
        sessions.forEach((userId, mysession) -> {
            System.out.println("用户ID: " + userId);
            System.out.println("Session ID: " + mysession.getId());
            System.out.println("是否开启: " + mysession.isOpen());
            System.out.println("------------------------");
        });
        try {
            // 解析收到的消息
            JSONObject jsonMessage = JSON.parseObject(message);
            String type = jsonMessage.getString("type");
            
            // 根据消息类型处理
            switch (type) {
                case "JOIN":
                    handleJoinMessage(jsonMessage, session);
                    break;
                case "CHAT":
                    handleChatMessage(jsonMessage, session);
                    break;
                case "LEAVE":
                    handleLeaveMessage(jsonMessage, session);
                    break;
            }
        } catch (Exception e) {
            System.out.println("处理消息异常：" + e.getMessage());
        }
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("WebSocket发生错误：" + error.getMessage());
        sessions.remove(session.getId());
    }
    
    // 处理用户加入消息
    private void handleJoinMessage(JSONObject message, Session session) {
        // 保存用户信息到session
        session.getUserProperties().put("userId", message.getString("userId"));
        session.getUserProperties().put("username", message.getString("username"));
        
        // 广播用户加入消息
        JSONObject broadcastMessage = new JSONObject();
        broadcastMessage.put("type", "JOIN");
        broadcastMessage.put("userId", message.getString("userId"));
        broadcastMessage.put("username", message.getString("username"));
        broadcastMessage.put("message", message.getString("username") + " 加入了聊天");
        broadcastMessage.put("timestamp", System.currentTimeMillis());
        
        broadcastMessage(broadcastMessage.toJSONString());
    }
    
    // 处理聊天消息
    private void handleChatMessage(JSONObject message, Session session) {
        String receiverId = message.getString("receiverId");
        
        if (!"".equals(receiverId)) {
            // 私聊消息
            System.out.println("私聊");
            sendToUser(receiverId, message.toJSONString());
        } else {
            // 广播消息
            broadcastMessage(message.toJSONString());
        }
    }
    
    // 处理用户离开消息
    private void handleLeaveMessage(JSONObject message, Session session) {
        String username = (String) session.getUserProperties().get("username");
        
        JSONObject leaveMessage = new JSONObject();
        leaveMessage.put("type", "LEAVE");
        leaveMessage.put("userId", message.getString("userId"));
        leaveMessage.put("username", username);
        leaveMessage.put("message", username + " 离开了聊天");
        leaveMessage.put("timestamp", System.currentTimeMillis());
        
        broadcastMessage(leaveMessage.toJSONString());
    }
    
    // 发送消息给指定session
    private void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            System.out.println("发送消息异常：" + e.getMessage());
        }
    }
    
    // 广播消息给所有连接的客户端
    private void broadcastMessage(String message) {
        sessions.values().forEach(session -> {
            sendMessage(session, message);
        });
    }
    
    // 发送消息给指定用户
    private void sendToUser(String userId, String message) {
        sessions.values().stream()
            .filter(session -> userId.equals(session.getUserProperties().get("userId")))
            .findFirst()
            .ifPresent(session -> sendMessage(session, message));
    }
}